package com.itita.ww2.utils.channel;

import com.itita.ww2.enums.ChannelEnum;
import com.itita.ww2.utils.channel.facebook.FBTokenVerifier;
import com.itita.ww2.utils.channel.facebook.FBTokenVerifier.Builder.AccessType;
import com.itita.ww2.utils.channel.facebook.FBUserInfo;
import com.itita.ww2.utils.channel.google.GoogleAuthCodeVerifier;
import com.itita.ww2.utils.channel.google.GoogleUserInfo;
import com.itita.ww2.utils.properties.ServerProperties;

public class ChannelUtil {

	/**
	 * 验证并获取唯一id
	 */
	public static String getChannelId(int channel, String token) {
		ChannelEnum channelEnum = ChannelEnum.valueOf(channel);
		String channelId = null;
		switch (channelEnum) {
		case FACEBOOK:
			{
				String clientId = ServerProperties.getString("fb_client_id");
				String clientSecret = ServerProperties.getString("fb_client_secret");
				// @formatter:off
				FBTokenVerifier verifier = new FBTokenVerifier.Builder(clientId, clientSecret)
						.setAccessType(AccessType.ME)
						.setUseGenericAccessToken(false)
						.build();
				// @formatter:on
				if (ServerProperties.getBoolean("proxy.enable")) {
					verifier.getBuilder().setProxy(ServerProperties.getString("proxy.type"),
							ServerProperties.getString("proxy.ip"), ServerProperties.getInt("proxy.port"));
				}

				FBUserInfo info = verifier.verify(token);
				if (info.isSucc()) {
					channelId = info.getId();
				}
			}
			break;
		case GOOGLE:
			{
				// 通过idToken验证登录,并获取userId (subject)
				String clientId = ServerProperties.getString("google_client_id");
				String clientSecret = ServerProperties.getString("google_client_secret");
				String appId = ServerProperties.getString("google_appId");

				// @formatter:off
				GoogleAuthCodeVerifier verifier = new GoogleAuthCodeVerifier.Builder(clientId, clientSecret, appId)
						.build();
				// @formatter:on

				if (ServerProperties.getBoolean("proxy.enable")) {
					verifier.getBuilder().setProxy(ServerProperties.getString("proxy.type"),
							ServerProperties.getString("proxy.ip"), ServerProperties.getInt("proxy.port"));
				}

				GoogleUserInfo info = verifier.verify(token);
				if (info.isSucc()) {
					channelId = info.getId();
				}
			}
			break;
		case TWITTER:
			// 暂时不绑
			break;
		default:
			// 渠道号错误
			break;
		}
		return channelId;
	}
}
